package scau.online.web.user;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import scau.cty.base.common.BaseController;
import scau.cty.base.common.IBaseService;
import scau.cty.base.util.PasswordHelper;
import scau.cty.base.util.PhoneKeyUtil;
import scau.cty.dictionary.Code;
import scau.cty.entity.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/26.
 */

@Api(value = "注册接口",description = "注册相关接口")
@RestController
@RequestMapping(value = "/register",produces = "application/json")
public class RegisterController extends BaseController{

    @Autowired
    private IBaseService<User> userIBaseService;

    /**
     * 验证账号是否已存在
     * @param username
     * @return
     */
    @ApiOperation(value = "检查手机号码是否已注册")
    @ApiImplicitParams({@ApiImplicitParam(name = "username",value = "注册的手机号码",required = true,dataType = "String",paramType = "query")})
    @GetMapping("/check_username")
    @ResponseBody
    public String getCheckUsername(String username){
        Map map = new LinkedHashMap();
        if(username == null || username ==""){
            sendCode(map, Code.ILLEGAL_DATA_ERROR); // 返回码4 非法参数
            return JSON.toJSONString(map);
        }
        if(userIBaseService.findSelectPropertyWhereAnd("username",username).size() == 0){
            sendCode(map,Code.USER_SUCCESS); // 返回码9 可以注册
            return JSON.toJSONString(map);
        }else {
            sendCode(map,Code.USER_EXIST); //返回码8 该账号已被注册
            return JSON.toJSONString(map);
        }

    }

    /**
     * 发送手机验证码  短信模板id SMS_58050195
     * @param request
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "发送手机验证码")
    @ApiImplicitParams({@ApiImplicitParam(name = "username",value = "注册的手机号码",required = true,dataType = "String",paramType = "query")})
    @PostMapping("/send_key")
    public String sendPhoneKey(HttpServletRequest request, String username){
        Map map = new LinkedHashMap();
        String phoneKey = PhoneKeyUtil.getRandomNumber(); //生成随机四位数字
        String smsParamString = "{\"phoneKey\":\"" + phoneKey + "\"}"; //传验证码进入短信模板
        PhoneKeyUtil.sendPhoneKeyUtils(username,username,smsParamString,"SMS_58050195"); //发送验证码
        HttpSession session = request.getSession();
        session.setAttribute("phoneKey",phoneKey);  //保存 生成的四位数字
        session.setAttribute("phoneNumber",username); //保存发送的手机号码  以便后面验证
        String phoneKey1  = (String) session.getAttribute("phoneKey");
        System.out.println("已存入session"+phoneKey1);
        sendCode(map,Code.OPERATION_SUCCESS);
        return JSON.toJSONString(map);
    }

    /**
     * 注册接口 确保手机号码和发送验证码的一致性
     * 要求验证账号和密码的格式正确性
     * 对密码加密 设置创建时间和账号的权限等级
     * @param request
     * @param user
     * @param phoneKey
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "执行注册(需验证格式先)")
    @ApiImplicitParams({@ApiImplicitParam(name = "username",value = "注册的手机号码",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "password",value = "密码",required = true,dataType = "String",paramType = "query"),
        @ApiImplicitParam(name = "phoneKey",value = "用户输入的验证码",required = true,dataType = "String",paramType = "query")
    })
    @PostMapping("/add_user")
    public String registerNewUser(HttpServletRequest request, User user,String phoneKey){
        Map map = new LinkedHashMap();
        HttpSession session = request.getSession();
        if(userIBaseService.findSelectPropertyWhereAnd("username",user.getUsername()).size() == 1){
            sendCode(map,Code.USER_EXIST); // 返回码8 用户已被注册
            return JSON.toJSONString(map);
        }
        String phoneKey2 = (String) session.getAttribute("phoneKey"); //取出发送的手机验证码
        String phoneNumber = (String) session.getAttribute("phoneNumber"); //取出发送的手机号码
        System.out.println("获取到的信息"+user.getUsername()+"~~"+user.getPassword()+"~~"+phoneKey+"存的"+phoneNumber+"~"+phoneKey2 );
        if(!user.getUsername().equals(phoneNumber) || !phoneKey2.equals(phoneKey) ){
            //若验证码不正确 或者验证码不是对应发送的手机号码 则添加失败
            sendCode(map,Code.PHONECODE_ERROR); // 返回码 10 手机验证码 错误
            return JSON.toJSONString(map);
        }
        if(user.getUsername().matches("^[\\\\0-9]{11}$") && user.getPassword().matches("^[\\\\a-zA-Z0-9-]{6,16}$")){
            // 满足格式要求  账号为11位手机号码  密码位6-16位英文数字
            PasswordHelper.encryptPassword(user); //加密
            user.setCreateTime(new Date());
            user.setRoleRank(1);  // 账号权限等级
            userIBaseService.add(user);
            sendCode(map,Code.OPERATION_SUCCESS);
            return JSON.toJSONString(map);
        }else {
            sendCode(map,Code.ILLEGAL_DATA_ERROR); //格式错误 返回码4 非法参数
            return JSON.toJSONString(map);
        }

    }

}
